ASP.NET – Fill and Show Dependent drop down list on Client side without server control and Postback

In this post we will look into filling dependent drop down list(s) on client side without using server side asp:dropdownlist control and autopostback, which is the common way we see around. We will be using jQuery at the front end to do the drop down list marp-up generation and adding data to it. We will be using WebMethod to retrieve JSON data from the server where we can return simple data types or any Enumerable data types like List etc so it fills the regular or common way of server side implementation where we use a service method or so to retrieve object collection from DB or from application code itself.

Please find the code snippet below which represents aspx page code behind file and app code file where collection is returned which can be replaced with a service layer call querying DB to get the collection back to presentation layer:

1) ASPX Page with jQuery Code


<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title></title>
    <script src="jquery-1.2.6.js" type="text/javascript"></script>
    <% if (false)
       { %>
    <script src="jquery-1.2.6-vsdoc.js" type="text/javascript"></script>
    <% }%>
    
    <link href="DefaultStyleSheet.css" rel="stylesheet" type="text/css" />
    
    <script type="text/javascript">

        //Write your code when Document is loaded
        $(document).ready(function() {
            $("#ddl2").hide(0, function() { });
            //Code to append a drop down list at client end
            //$("#ddl1").append("<option value=\"new\">new</option>");            

            //event to be fired when an option\index gets changed for first drop down list
            $("#ddl1").change(function() {
                $("#ddl2").fadeOut(1500, function() { });
                var value = $(this).val();
                //alert(value);
                $("#waitingBlock").css({ "margin-left": "10px" });
                $("#waitingBlock").html("<img src='spinner.gif' alt='loading....' />")
                .fadeIn(1500)
                .insertAfter($("#ddl1"));
                
                //Client side function call which will make ajax request for page method named FillDD to get json data
                FillDDProxy("FillDD", ["selectedDDItem", value]);
            });
        });

                
        function FillDDProxy(methodName, paramArray, errorFunction) {
            var pagePath = window.location.pathname;
            var paramList = '';

            if (paramArray.length > 0) {
                for (var i = 0; i < paramArray.length; i += 2) {
                    if (paramList.length > 0) paramList += ',';
                    paramList += '"' + paramArray[i] + '"' + ':' + '"' + paramArray[i + 1] + '"';
                }
            }
            paramList = '{' + paramList + '}';
            
            //Call the page method
            $.ajax({
                type: "POST",
                url: pagePath + "/" + methodName,
                contentType: "application/json; charset=utf-8",
                data: paramList,
                dataType: "json",
                success: function(msg) {
                    successFunction(msg.d);
                }

            });
            return false;
        }
        
        function successFunction(msg) {
            
            $("#waitingBlock").fadeOut(1500, function() { });
            var list = msg.toString();            
            var strArray = list.split(",");
            //clear previously filled second drop down.
            $("#ddl2").children().remove();
            if (strArray.length > 0) {
                for (var i = 0; i < strArray.length; i++) {
                    //Filling the second drop down on client side with returned json data
                    $("#ddl2").append('<option value=\"' + strArray&#91;i&#93; + '">' + strArray[i] + '</option>');
                }
            }
            $("#ddl2").show(1500, function() { });            
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:DropDownList runat="server" ID="ddl1">
        <asp:ListItem Value="d1v1" Text="d1v1"></asp:ListItem>
        <asp:ListItem Value="d1v2" Text="d1v2"></asp:ListItem>
        <asp:ListItem Value="d1v3" Text="d1v3"></asp:ListItem>
        <asp:ListItem Value="d1v4" Text="d1v4"></asp:ListItem>
    </asp:DropDownList>
    
    <%--<asp:DropDownList runat="server" ID="ddl2"></asp:DropDownList>--%>
    <select id="ddl2" ></select>
    
    <span id="waitingBlock"></span>
    </div>
    <div>
    </div>
    </form>
</body>
</html>

2) Code behind C# file

using System;
using System.Web.Services;
using System.Collections;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    [WebMethod]
    public static IEnumerable FillDD(string selectedDDItem)
    {
        //Instantiate your service class or call your service layer method directly in case it is also static
        lib serviceLib = new lib();
        return serviceLib.getDDValues(selectedDDItem);
    }
}

I have used App_Code to represent service layer method:

3) App_Code\lib.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

/// <summary>
/// Summary description for lib
/// </summary>
public class lib
{
	public lib()
	{
		//
		// TODO: Add constructor logic here
		//
	}

    public List<string> getDDValues(string currentValue)
    {
        //use the currentValue to get dependent DD values from DB
        //I am putting them here hardcoded to reprenst the same.
        
        List<string> listString = new List<string>();
        listString.Add(currentValue);
        listString.Add("Sushant");
        listString.Add("RampGroup");
        
        return listString;
    }
}

Overall this code results into a beutiful animated dependent drop down showing and fading from ui depending upon the selection of first drop down. This overall is more performant that the postback as round trip is save with partial trip and also the mode of data transfer is thin JSON. On the client side rendering of this JSON data, it can be achieved either by using jQuery as shown in my example or else using jTemplates and then setting as data for the template. I will share the code in another post with use of jTemplates which can be of great help in scenarios where server side data controls like repeater or data grids are used and which can be replaced by the usage of jTemplates and doing a client side binding of the same with thin JSON data.

So, If you are looking into doing a AJAX and JSON call this example can help you along with an implementation of filling a dependent drop down.

Hope this helps!

bye for now

-Sushant

6 Responses to ASP.NET – Fill and Show Dependent drop down list on Client side without server control and Postback

  1. […] ASP.NET – Fill and Show Dependent drop down list on Client side … […]

  2. […] Continued here: ASP.NET – Fill and Show Dependent drop down list on Client side … […]

  3. Aaron says:

    Nice post…the code looks well written. I wish there was a working demo to see the exact effect. I’m having a hard time picturing what’s going on here.

  4. Nilesh says:

    Nice Post!!

    But I doubt whether it will retain value added at client side across postback.

  5. Vikram says:

    Hey this is good post!!!

    The code is look good,please post more post

  6. Paul says:

    I’m gone to say to my little brother, that he should also pay a visit this website on regular basis to get
    updated from hottest reports.

Leave a comment

Who am I what am I doing?

Who am I what am I doing?